import { createSlice } from "@reduxjs/toolkit";
import { setStorage, getStorage, removeStorage } from "../storage";
import { setToken, getToken, removeToken } from "@/utils/token";

const CACHE_KEY = "app_user";

export const counterSlice = createSlice({
  name: "user",
  initialState: {
    value: getStorage(CACHE_KEY) || {},
    token: getToken(),
  },
  reducers: {
    setUser: (state, action) => {
      state.value = action.payload;
      setStorage(CACHE_KEY, action.payload);
    },
    setUserToken: (state, action) => {
      state.token = action.payload;
      setToken(action.payload);
    },
    removeUser: (state) => {
      state.value = {};
      state.token = { accessToken: "", refreshToken: "" };
      removeStorage(CACHE_KEY);
      removeToken();
    },
  },
});

export const { setUser, removeUser, setUserToken } = counterSlice.actions;

export default counterSlice.reducer;
